<template>
  <view class="wrapperBA">
    <view class="BA_item_top">
      <text>{{ objData.elevatorName }}</text>
      <text>{{ objData.elevatorAddress || objData.elevatorName }}</text>
    </view>
    <view class="main">
      <view class="mainBox">
        <view class="BA_item_type" v-if="workShow">
          <view class="title">任务类型<text>*</text></view>
          <view class="btnBox">
            <view class="btn" v-for="(item, index) in btnBoxLists" :key="index">
              <view :class="['btnItem', workOrderType == item.key ? 'btnSel' : '']"
                @click="selectBtn(item.key, 'workOrderType')">
                {{ item.label }}</view>
            </view>
          </view>
        </view>
        <view class="BA_item_type" v-if="emerShow">
          <view class="title">紧急程度<text>*</text></view>
          <view class="btnBox">
            <view class="btn" v-for="(item, index) in btnBoxList" :key="index">
              <view :class="['btnItem', emerProcType == item.key ? 'btnSel' : '']"
                @click="selectBtn(item.key, 'emerProcType')">
                {{ item.label }}</view>
              <!-- 
                  <view :class="['btnItem', emerProcType == item.key ? 'btnSel' : '']"
                    @click="selectBtn(item.key, 'emerProcType')" :style="{
                      color: item.key == 1 ? '#E02020' : '',
                      borderColor:
                        emerProcType == 1 && item.key == 1 ? '#E02020' : '',
                    }">
                    {{ item.label }}</view>
                 -->
            </view>
          </view>
        </view>
        <view class="BA_item_type">
          <view class="title">报障电梯状态<text>*</text></view>
          <helangcheckbox class="helange-btns" ref="checkStatus" :isShows="true" keyName="faultArr"
            @change="onChange" />
        </view>
      </view>
      <view class="BA_item_info">
        <view class="title">
          <view class="info_head">故障信息<text>*</text></view>
          <!--
          <view style="display: flex; align-items: center">
            <view :class="['radio', isOpen ? 'selected' : '']" @click="openPart" v-if="index == 0">
              <view :class="[isOpen ? 'right-check right-bg' : 'right-check']"></view>
              报电梯部件故障
            </view>
            <image v-if="works.length > 1" src="@/static/images/delete.png" @click="delMsg(index)" style="
                width: 32rpx;
                height: 32rpx;
                cursor: pointer;
                margin-left: 20rpx;
              "></image>
          </view>
          -->
        </view>
        <view class="btnBox">
          <view class="btn">
            <view :class="['btnItem', !isOpen ? 'btnSel' : '']" @click="comfire">整梯报障</view>
          </view>
          <view class="btn">
            <view :class="['btnItem', isOpen ? 'btnSel' : '']" @click="comfire">部件报障</view>
          </view>
        </view>
        <!--
        <view class="item_partsModel">
          <view class="title">报障人<text style="color: red">*</text></view>
          <view class="partsNumber_input">
            <input type="text" placeholder="请输入报障人" v-model="item.name" placeholder-style="color:#ccc"
              :disabled="false" />
          </view>
        </view>
        <view class="item_partsModel">
          <view class="title">联系电话<text style="color: red">*</text></view>
          <view class="partsNumber_input">
            <input type="text" placeholder="请输入联系电话" v-model="item.phone" placeholder-style="color:#ccc"
              :disabled="false" />
          </view>
        </view>
      -->
        <view v-for="(item, index) in works" :key="index" class="repeatBox">
          <block v-if="isOpen || (!isOpen && index == 0)">
            <view class="repeatBox_item" v-if="isOpen">
              <view class="serial-num">{{ index + 1 }}</view>
              <view v-if="works.length > 1" class="handleBtn" @click="delMsg(index)">
                <image src="@/static/images/delete.png"></image>
                <view class="delBtn">删除</view>
              </view>
            </view>
            <view class="item_partsModel" v-if="!isOpen">
              <view class="title">故障现象<text>*</text></view>
              <view class="falutContent">
                <view class="falutItemBox" v-for="(it, i) in falutList" :key="it.dictKey">
                  <view :class="[
                    'falutItem',
                    item.problemItem.includes(it.dictKey) ? 'active' : '',
                  ]" @click="clickFaultItem(item, it, i)">
                    {{ it.dictValue }}
                  </view>
                </view>
              </view>
              <input type="text" v-if="item.problemItem.includes(otherId)" placeholder="请输入其他故障现象" class="other"
                v-model="item.problemOtherDesc" />
            </view>
            <view v-else class="item_partsModel">
              <view class="title">电梯部件<text>*</text></view>
              <view class="partsNumber_select" @click="selectPartsClick(index)">
                <!-- <view class="partsNumber_input" @click="selectPartsClick(index)">
                    <uni-easyinput type="textarea" autoHeight v-model="item.partsNames" placeholder="请选择配件" placeholder-style="color:#ccc"
                    :disabled="true"></uni-easyinput>
                </view> -->
                <view class="innerText" :style="item.partsNames ? 'color:#333' : ''">
                  {{ item.partsNames || '请选择配件' }}
                  <text v-if="item.partsNames && item.floorStandNames">({{ item.floorStandNames.replaceAll(',','>') }})</text>
                </view>
                <view class="downs"><text></text></view>
              </view>

            </view>
            <view class="item_desc">
              <view class="title">故障描述<text>*</text></view>
              <view>故障描述或者故障图片/视频其中一项必须填写</view>
            </view>
            <view class="areaBox">
              <textarea v-model="item.mfDesc" @blur="bindTextAreaBlur(item, $event)" maxlength="300"
                placeholder="请输入故障描述" />
              <view class="info_num" :style="{ color: item.NumStr >= 300 ? '#e02020;' : '#666666;' }">{{ item.NumStr
                }}/300
              </view>
            </view>
            <view class="info_img">
              <view>图片/视频({{ item.mfImgUrl.length }}/9)</view>
              <imageDragSort max="9" :list="item.mfImgUrl" @changeList="changeImg(item, $event)" tips="上传图片"
                @getPopUpVisible="getPopUpVisible">
              </imageDragSort>
              <text v-if="item.tipsState">必须提交描述或者故障图片/视频其中一项，方能提交</text>
            </view>
          </block>
        </view>
        <view class="addMessage" v-if="isOpen" @click="addMsg">
          <image src="@/static/images/addService.png"></image>
          <view class="label">添加报障部件</view>
        </view>
      </view>
      <view class="BA_item_person">
        <view class="title">计划完成时间
          <text class="sign">*</text>
        </view>
        <view class="btnBox">
          <view class="btn">
            <view :class="['btnItem', isTimeOpen === 1 ? 'btnSel' : '']" @click="comTime(1)">无</view>
          </view>
          <view class="btn">
            <view :class="['btnItem', isTimeOpen === 2 ? 'btnSel' : '']" @click="comTime(2)">其他时间</view>
          </view>
        </view>
        <view class="timeSe" v-if="isTimeOpen === 2">
          <uni-icons type="calendar" color="#c0c4cc" size="22"></uni-icons>
          <input @click="comTime(3)" type="text" class="time_input" v-model="beginTime" :disabled="true"
            placeholder="请选择时间" />
        </view>
      </view>
      <view class="BA_item_person">
        <view class="title">{{ userinfo.role_name == "maintenance" ? "任务指派" : "任务指派" }}
          <text class="sign">*</text>
        </view>
        <view class="btnBox" v-if="userinfo.role_name == 'maintenance'">
          <view class="btn" v-for="(item, index) in ['指派任务', '转审批']" :key="index" @click="handleAssign(item, index)">
            <view :class="['btnItem', activeIndex == index ? 'btnSel' : '']">
              {{ item }}
            </view>
          </view>
        </view>
        <view class="person" @click="personClick">
          <view class="personL" v-if="userinfo.role_name != 'maintenance'">已选人员</view>
          <view class="personL" v-else>已选人员</view>

          <view class="personR" v-if="userinfo.role_name != 'maintenance'">
            <text v-if="checkArrUser.length <= 0">请选择人员</text>
            <view v-else>
              <block v-for="(item, index) in checkArrUser" :key="index">
                <text>{{ item.title + " " }}</text>
              </block>
            </view>

            <text class="rightTo"></text>
          </view>
          <!-- 维保员显示人员名称 -->
          <view class="personR" v-else>
            {{
              activeIndex == 0
                ? userinfo.nick_name
                : groupObj.groupApproveNames || "--"
            }}
          </view>
        </view>
      </view>
      <view class="BA_item_tips">
        {{
          userinfo.role_name == "maintenance"
            ? activeIndex == 0
              ? "提示：当前身份为维保员-任务只能指派给自己，新建报障后，可直接执行维修任务"
              : "提示：提交报障后，将由上级进行审批，可在-个人头像-我的申请-维修报障，查看提交的报障申请"
            : "提示：新建报障后，可在我的审批-维修报障-查看分配的报障任务"
        }}
      </view>
      <view class="BA_item_botm" @click="submitClicksr" v-if="showSubmit">
        <view :class="btnStatus ? 'botms' : 'botm'">{{
          userinfo.role_name == "maintenance" ? "创建任务" : "新建任务"
        }}</view>
      </view>
      <model title=" " comfireTxt="确认" :maskClick="false" @cancle="visibleShow = false" @comfire="comfire"
        :visible="visibleShow">
        <view class="comfirBox">
          <view>{{
            isOpen
              ? "是否不再对电梯部件进行故障描述？"
              : "是否对电梯部件进行故障描述？"
          }}</view>
          <view>注:点击确认后，原本所输入的信息将被清空</view>
        </view>
      </model>

      <neilmodal :show="show" @close="closeModal" title="指派人员" @cancel="cancelClick" @confirm="confirmClick">
        <view class="radioLR">
          <view class="radio_R">
            <view><uni-data-checkbox multiple :wrap="true" :isShowBarr="true" :localdata="range"
                @change="radioClick"></uni-data-checkbox></view>
          </view>
        </view>
      </neilmodal>
    </view>
    <!-- 点定义选择时间 -->
    <time-select :atterToday="true" :beforeToday="false" :isChooseToday="true" :singStatus="true" v-if="selectTimePopup"
      @close="closeSelectTimePopup"></time-select>
    <previewMedia ref="previewMedia"></previewMedia>
  </view>
</template>

<script>
import helangcheckbox from '@/components/helang-checkbox/helang-checkbox.vue';
import model from '@/components/model/index.vue';
import imageDragSort from '@/components/image-drag-sort/img-and-video.vue';
import neilmodal from '@/components/neil-modal/neil-modal.vue';
// import unipopup from '@/components/uni-popup/uni-popup';
import timeSelect from '@/pages/index/components/timeSelect.vue';
import uniIcons from '@/components/uni-icons/uni-icons.vue';

import {
	problemItem,
	malfunctionWorkContent,
	getApproveUserData,
	getReform, malfunctionWorkContentV2,
} from '@/apis/barrierSearch.js';
import { throttle, hanleToken } from '@/utils/utils.js';
import { mapState, mapActions } from 'vuex';
import dayjs from 'dayjs';
import {rescueDetail} from '@/apis/elevator';
function isValid(val) {
	let phone = /^1(3|4|5|6|7|8|9)\d{9}$/;
	let tel = /^(\(\d{3,4}\)|\d{3,4}-|\s)?\d{4,8}$/;
	if (phone.test(val) || tel.test(val)) {
		return true;
	}
	return false;
}
export default {
	name: 'barrierPage',
	data() {
		return {
			// 切换至整体报障提示
			visibleShow: false,
			workOrderType: '',
			emerProcType: '',
			show: false,
			range: [],
			// BuilData:"",
			objData: {},
			// 安全类
			securityArr: {},
			// 电梯状态
			faultArr: {},
			btnStatus: false,
			falutActive: '',
			// 故障现象总集合
			falutList: [],
			showSubmit: true,
			// 组长信息
			groupObj: {},
			// 分配任务人员
			checkArrUser: [],
			activeIndex: 0,
			btnBoxList: [
				// 紧急程度标签
				{ color: '#e02020', bgColor: '#ffecec', label: '非常紧急', key: '1' },
				{ color: '#fa6400', bgColor: '#ffecdf', label: '紧急', key: '2' },
				{ color: '#F7B500', bgColor: '#fff7e1', label: '普通', key: '3' },
				{ color: '#0091FF', bgColor: '#dcf0ff', label: '较低', key: '4' },
			],
			btnBoxLists: [
				// 任务类型标签
				{ color: '#0091FF', bgColor: '#dcf0ff', label: '内部整改', key: '1' },
				{ color: '#F7B500', bgColor: '#fff7e1', label: '客户报障', key: '2' },
			],
			isOpen: false,
			otherId: '',
			works: [
				{
					name: '',
					phone: '',
					mfImgUrl: [],
					// 故障描述
					mfDesc: '',
					// 选择故障现象的集合
					problemItem: [],
					problemOtherDesc: '',
					// 字符数量
					NumStr: 0,
					// 提示验证
					tipsState: false,
					// 配件数据
					partsSelectArr: [],
					customArrs: [],
					partsNames: '',
					showCustom: false,
				},
			],
			// 缓存整梯报障数据
			allWorks: [],
			// 缓存部件报障数据
			unitWorks: [],
			partIndex: 0,
			// 是否展示 任务类型
			workShow: true,
			// 是否展示 紧急程度
			emerShow: true,
			// 整改任务问题点的id
			malHistoryId: '',
			// 质检工单的id,
			fromPlanId: '',
			// 任务来源 [{ name: "保养", id: 1 },{ name: "维修", id: 2 },
			//  { name: "救援", id: 3 },{ name: "配件", id: 4 },{ name: "事务", id: 5 },
			// { name: "质检", id: 6 },{ name: "评分", id: 7 }, { name: "年审", id: 8 },]
			sourcePlanType: 2,
			isTimeOpen: 1,
			selectTimePopup: false,
			beginTime: '',
			endTime: '',
			rescueNoticeId:'',
			rescueDetailData:null // 救援详情数据
		};
	},
	components: {
		helangcheckbox,
		imageDragSort,
		neilmodal,
		model,
		// unipopup,
		timeSelect,
		uniIcons
		// unidatacheckbox
	},
	computed: {
		...mapState('user', ['userinfo']),
	},
	async onLoad(opt) {
		this.rescueNoticeId = opt.rescueNoticeId || '';
		// 紧急程度标签顺序反转
		this.btnBoxList.reverse();

		console.log('opt', opt);
		if (opt.wokrType == 1 && opt.trapFormValue != '维保端报警') {
			this.workOrderType = 2;
			this.emerProcType = 1;
			this.workShow = false;
			this.emerShow = false;
		}
		if (opt.type == 1) {
			this.workOrderType = 1;
			this.workShow = false;
		}
		this.works[0].name = this.userinfo.nick_name;
		this.works[0].phone = this.userinfo.phone;
		this.fromPlanId = opt.planId || '';
		this.getProblemItem();
		// this.BuilData = JSON.parse(opt.BuilData)
		this.objData = opt.elevatorId ? opt : JSON.parse(opt.params);
		this.works[this.partIndex].floorStandIds = this.objData.floorStandIds;
		this.works[this.partIndex].floorStandNames = this.objData.floorStandNames;
		this.range = [
			{ value: 0, text: this.userinfo.nick_name || '', selected: true },
		];

		// #ifdef H5
		setTimeout(() => {    
			this.$refs.checkStatus.set({
				type: 'radio',
				index: 0,
				list: [
					{ id: 1, dictValue: '正常运行' },
					{ id: 2, dictValue: '停梯' },
				],
			});
		}, 100);
		// #endif

		// #ifndef H5
		this.$refs.checkStatus.set({
			type: 'radio',
			index: 0,
			list: [
				{ id: 1, dictValue: '正常运行' },
				{ id: 2, dictValue: '停梯' },
			],
		});
		// #endif

		// 如果有malHistoryId是发起整改任务
		if (opt.malHistoryId) {
			this.malHistoryId = opt.malHistoryId;
			this.workOrderType = 1;
			// 获取发起整改详情
			let obj = await this.getReformFun();
			console.log(obj, 'obj的值');
			this.emerProcType = obj.emerProcType;
			this.isOpen = true;
			this.works[0].partsNames = obj.partNames.split('&amp;&amp;').join('>');
			this.works[0].partsIds = obj.partIds;
			this.works[0].mfDesc = `问题分类:${obj.faultReasonClassifiedName};\n问题原因:${obj.faultReasonName};\n问题负责:${obj.faultReasonWhoName};\n问题描述:${obj.disposeDesc}`;
			this.works[0].mfImgUrl = obj.disposeImgUrl;
			this.fromPlanId = obj.planId;
		}
		// if(opt.emerProcType){
		//   this.emerProcType=opt.emerProcType
		//   console.log(this.emerProcType,"紧急程度")
		// }
		// 获取页面来源设置任务来源
		if (opt.formPage) {
			this.workOrderType = 1;
			switch (opt.formPage) {
			// 救援
			case 'rescue':
				if (this.fromPlanId) {
					this.getRescueDetail();
				}
				this.sourcePlanType = 3;
				this.emerProcType = 1;
				this.workOrderType = 2;
				break;
				// 保养
			case 'maintain':
				this.sourcePlanType = 1;
				break;
				// 质检
			case 'quality':
				this.sourcePlanType = 6;
				break;
			default:
				// 默认为维修
				this.sourcePlanType = 2;
				this.workOrderType = 2;
				break;
			}
		}
		this.initGetUserInfos();
		// #ifndef H5
		uni.$on('part-selectd', (res) => {
			this.partsSubmit(res);
		});
		// #endif

		// #ifdef H5
		setTimeout(() => {
			uni.$on('part-selectd', (res) => {
				this.partsSubmit(res);
			});
		}, 1000);
		// #endif
		await this.handleRreshToken();
	},
	watch: {

	},
	onShow() {
		let arr = hanleToken('get', 'planUserArr') || [];
		// 数据去重
		let obj = {};
		let peon = arr.reduce((cur, next) => {
			obj[next.id] ? '' : (obj[next.id] = true && cur.push(next));
			return cur;
		}, []);
		this.checkArrUser = peon;
	},

	onUnload() {
		hanleToken('remove', 'planUserArr');
		uni.$off('part-selectd');
	},
	methods: {
		...mapActions('user', ['handleRreshToken']),
		// 获取救援详情
		getRescueDetail() {
			uni.showLoading({
				title: '加载中',
				icon: 'none',
			});
			return new Promise((resolve) => {
				rescueDetail({ planId: this.fromPlanId }).then((res) => {
					if (res) {
						this.rescueDetailData = res.data;
						this.createMaintenance();
						uni.hideLoading();
					}
					resolve();
				});
			});
		},
		// 创建维修工单
		createMaintenance() {
			try {
				// 根据详情接口数据构造救援单信息
				const rescueUserInfo = this.rescueDetailData.rescueMessageVO || {};
				if (rescueUserInfo.name && rescueUserInfo.phone) {
					this.works[0].name = rescueUserInfo.name;
					this.works[0].phone = rescueUserInfo.phone;
				}
				this.works[0].problemItem = ['12'];
				this.works[0].emerProcType = 1;
				this.works[0].problemOtherDesc = '困人';
				this.works[0].mfDesc = '困人';
				this.works[0].tipsState = false;
				this.works[0].NumStr = this.bindTexStr(this.works[0].mfDesc , 250);
				this.works[0].planFrom = this.getReportChannelCode(rescueUserInfo.trapFrom);
				// #ifdef H5
				setTimeout(() => {
					this.$refs.checkStatus.set({
						type: 'radio',
						index: Number(this.rescueDetailData.isStop) === 2 ? 1 : 0,
						list: [
							{ id: 1, dictValue: '正常运行' },
							{ id: 2, dictValue: '停梯' },
						],
					});
				}, 100);
				// #endif

				// #ifndef H5
				this.$refs.checkStatus.set({
					type: 'radio',
					index: Number(this.rescueDetailData.isStop) === 2 ? 1 : 0,
					list: [
						{ id: 1, dictValue: '正常运行' },
						{ id: 2, dictValue: '停梯' },
					],
				});
				// #endif
				console.log('详情页维修工单透传数据:', this.maintenanceFormData);
			} catch (error) {
				console.error('创建维修工单失败:', error);
			}
		},

		// 获取报障渠道代码 (对应tasksFromEdit中的worksPlanFrom字段)
		getReportChannelCode(rescueSource) {
			// 根据tasksFromEdit.vue中的报障渠道选项映射
			// 1-物业端报障 2-微信群报障 3-服务电话报障 4-系统派单 5-维保端报障 6-游客报障 7-WEB端报障 8-梯联网报障
			const channelMap = {
				'1_1': 3, // 服务电话报警 -> 服务电话报障
				'1_2': 5, // 维保端报警 -> 维保端报障
				'1_3': 8, // 梯联网报警 -> 梯联网报障
				'1_4': 1, // 物业端报警 -> 物业端报障
				'1_5': 2, // 微信群报警 -> 微信群报障
				'1_6': 9, // 一键呼救报警 -> 一键呼救报障
				'1_7': 10  // AI客服报警 -> AI客服报障
			};
			return channelMap[rescueSource] || 3; // 默认为服务电话报障
		},
		// 获取发起整改问题点的内容填充
		getReformFun() {
			return new Promise((reslove) => {
				getReform({ id: this.malHistoryId }).then((res) => {
					console.log(res.data, '问题点填充');
					reslove(res.data);
				});
			});
		},
		openPart() {
			this.visibleShow = true;
		},
		comfire() {
			// this.visibleShow = false;
			if (this.isOpen) {
				this.unitWorks = JSON.parse(JSON.stringify(this.works));
			} else {
				this.allWorks = JSON.parse(JSON.stringify(this.works));
			}
			let unitWorksNull = (this.unitWorks.length === 0);
			let allWorksNull = (this.allWorks.length === 0);
			if (unitWorksNull || allWorksNull) {
				this.works = [
					{
						name: this.userinfo.nick_name,
						phone: this.userinfo.phone,
						mfImgUrl: [],
						// 故障描述
						mfDesc: '',
						// 选择故障现象的集合
						problemItem: [],
						problemOtherDesc: '',
						// 字符数量
						NumStr: 0,
						// 提示验证
						tipsState: false,
						// 配件数据
						partsSelectArr: [],
						customArrs: [],
						partsNames: '',
						showCustom: false,
					},
				];
				if (unitWorksNull) {
					this.unitWorks = JSON.parse(JSON.stringify(this.works));
				} else {
					this.allWorks = JSON.parse(JSON.stringify(this.works));
				}
			}
			this.isOpen = !this.isOpen;
			this.works = JSON.parse(JSON.stringify((this.isOpen ? this.unitWorks : this.allWorks)));
			if (this.fromPlanId && this.rescueDetailData) {
				this.createMaintenance(this.rescueDetailData);
			}
		},
		// 获取故障现象
		// getProblemItem() {
		// 	problemItem().then((res) => {
		// 		console.log(res, '故障现象');
		// 		this.falutList = res.data;
		// 	});
		// },
		// 选择紧急程度
		selectBtn(val, key) {
			this[key] = val;
			this.$forceUpdate();
		},
		// 删除配件描述
		delMsg(index) {
			this.works.splice(index, 1);
		},
		// 添加电梯配件描述
		addMsg() {
			if (this.works.length >= 10) {
				uni.showToast({
					title: '故障描述最多添加10条',
					icon: 'none',
				});
				return;
			}
			let obj = {
				name: this.userinfo.nick_name,
				phone: this.userinfo.phone,
				mfImgUrl: [],
				// 故障描述
				mfDesc: '',
				// 选择故障现象的集合
				problemItem: [],
				problemOtherDesc: '',
				// 字符数量
				NumStr: 0,
				// 提示验证
				tipsState: false,
				// 配件数据
				partsSelectArr: [],
				customArrs: [],
				partsNames: '',
				showCustom: false,
			};
			if (this.rescueDetailData) {
				const rescueUserInfo = this.rescueDetailData.rescueMessageVO || {};
				if (rescueUserInfo.name && rescueUserInfo.phone) {
					obj.name = rescueUserInfo.name;
					obj.phone = rescueUserInfo.phone;
				}
			}
			this.works.push(obj);
		},
		// 配件搜索选择确定
		partsSubmit(res) {
			let names = res.names;
			let ids = res.ids;
			this.works[this.partIndex].partsIds = ids.join(',');
			this.works[this.partIndex].partsSelectArr = ids;
			this.works[this.partIndex].other = res.other || '';
			this.works[this.partIndex].partsNames = names.join('>');
			if (res.flag && res.flag.id) {
				this.works[this.partIndex].floorStandIds = res.flag.ids.join(',');
				this.works[this.partIndex].floorStandNames = res.flag.names.join(',');
			} else {
				delete this.works[this.partIndex].floorStandIds;
				delete this.works[this.partIndex].floorStandIds;
			}
		},

		// 选择紧急程度和任务类型
		// selectBtn(val, key) {
		// 	this[key] = val;
		// 	this.$forceUpdate();
		// },
		// 选择配件
		selectPartsClick(index) {
			this.partIndex = index;
			// this.$refs.popup.open();
			let disabledArr = [];
			// 禁止选择 已存在的部件
			if (this.works.length > 1) {
				disabledArr = this.works.map(item => {
					if (item.partsIds) {
						return {
							floorStandIds:item.floorStandIds,
							partsIds: item.partsIds.split(','),
							partsNames: item.partsNames ? item.partsNames.split('>') : []
						};
					} else {
						return {
							partsIds: [],
							partsNames: []
						};
					}
				});
			}
			uni.navigateTo({
				url: '/pages/pubilc/partSelect?disabledArr=' + JSON.stringify(disabledArr) + '&elevatorId=' + this.objData.elevatorId,
				fail: (fail) => {
					console.log(fail);
				},
			});
		},
		handleAssign(res, i) {
			this.activeIndex = i;
		},
		initGetUserInfos() {
			getApproveUserData({ submitId: this.userinfo.user_id }).then((res) => {
				console.log('xiaoyaaa', res);
				if (res.code === 200) {
					this.groupObj = res.data;
				}
			});
		},

		getPopUpVisible(e) {
			this.showSubmit = !e;
		},

		closeSelectTimePopup(val) {
			console.log('closeSelectTimePopup', val);
			if (val) {
				// 如果选择了时间范围
				if (val.includes('-')) {
					let ary = val.split('-');
					let start = ary[0].replaceAll('.', '-');
					// let end = ary[1].replaceAll('.', '-');
					// console.log(start,end,'开始和借宿')

					this.beginTime = start;
					// this.endTime = end;
				} else {
					// 如果选了单个日期
					const time = val.replaceAll('.', '-');

					this.beginTime = time;
					// this.endTime = time;

					console.log(time, dayjs().format('HH:mm:ss'), '单个日期');
				}
			} else {
				// 日期取消操作
				console.log('点击了自定义日期取消');
			}
			this.selectTimePopup = false;
		},

		comTime(type) {
			if (type === 3) {
				this.selectTimePopup = true;
				return;
			}
			this.isTimeOpen = type;
			if (type === 1) {
				this.beginTime = '';
			}
		},

		submitClicksr: throttle(function () {
			// console.log("提交");
			// return
			if (!this.workOrderType) {
				uni.showToast({
					title: '请选择任务类型',
					icon: 'none',
				});
				return;
			}
			if (!this.emerProcType) {
				uni.showToast({
					title: '请选择紧急程度',
					icon: 'none',
				});
				return;
			}
			if (this.btnStatus) {
				return;
			}
			for (let index = 0; index < this.works.length; index++) {
				const item = this.works[index];
				if (!item.name) {
					uni.showToast({
						title: '请输入报障人',
						icon: 'none',
					});
					return;
				}
				if (!isValid(item.phone)) {
					uni.showToast({
						title: '请正确输入手机号',
						icon: 'none',
					});
					return;
				}
				if (!this.isOpen && !item.problemItem.length) {
					uni.showToast({
						title: '请选择故障现象',
						icon: 'none',
					});
					return;
				}
				if (this.isOpen && !item.partsNames) {
					uni.showToast({
						title: '请选择电梯部件',
						icon: 'none',
					});
					return;
				}
				if (!this.isOpen && item.problemItem.includes(this.otherId)) {
					if (!item.problemOtherDesc) {
						uni.showToast({
							title: '请填写其他故障现象',
							icon: 'none',
						});
						return;
					}
				}
				if (item.mfImgUrl.length <= 0 && item.NumStr == 0) {
					item.tipsState = true;
					return;
				}
			}

			if (!this.beginTime && this.isTimeOpen === 2) {
				uni.showToast({
					title: '请选择时间',
					icon: 'none',
				});
				return;
			}

			if (this.userinfo.role_name != 'maintenance') {
				if (this.checkArrUser.length <= 0) {
					uni.showToast({
						title: '请选择维保员',
						icon: 'none',
					});
					return;
				}
			}
			this.works.forEach((item) => {
				if (!this.isOpen) {
					item.problemItem = item.problemItem.join(',');
				} else if (item.partsNames) {
					item.partsNames = (item.partsNames.split('>')).join('&&');
					delete item.problemItem;
				}
				// 默认维保端报障
				if (this.rescueDetailData) {
					item.planFrom = this.getReportChannelCode(this.rescueDetailData.rescueMessageVO.trapFrom) || 5;
				} else {
					item.planFrom = 5;
				}
			});
			let str = this.objData.elevatorName + this.objData.elevatorAddress;
			const params = {
				rescueNoticeId:this.rescueNoticeId,
				workOrderType: this.workOrderType,
				emerProcType: this.emerProcType,
				fromPlanId: this.fromPlanId || '',
				address: str || '',
				elevatorId: this.objData.elevatorId,
				elevatorStop: this.faultArr.id || 1,
				typeStatus: this.securityArr.id || 2,
				works: this.works,
				sourcePlanType: this.sourcePlanType || '',
				userIds:
          this.userinfo.role_name != 'maintenance' &&
            this.checkArrUser.length > 0 ? this.checkArrUser.map((item) => item.id) : this.activeIndex == 0 ? [this.userinfo.user_id] : [],
				parentUserIds:
          this.userinfo.role_name == 'maintenance' && this.activeIndex == 1 ? this.groupObj.approveIds.split(',') : [this.userinfo.user_id],
				planFinishDate: this.isTimeOpen === 2 ? this.beginTime + ' ' + dayjs().format('HH:mm:ss') : '',
			};
			// 如果是发起整改任务
			if (this.malHistoryId) {
				params.fromPlanId = this.fromPlanId;
				params.works[0].malHistoryId = this.malHistoryId;
			}
			console.log(params, 2525525525);
			// return 
			// return
			uni.showLoading({
				title: '提交中',
				mask: true,
			});
			let request = this.sourcePlanType === 3 && this.fromPlanId ? malfunctionWorkContentV2 : malfunctionWorkContent;
			request(params)
				.then((res) => {
					if (res.code === 200) {
						uni.hideLoading();
						uni.showToast({
							title: '创建成功',
							icon: 'none',
						});
						hanleToken('remove', 'planUserArr');
						this.$store.commit('refreshData', true);

						for (let i = 0; i < params.works.length; i++) {
							if (params.works[i].other) {
								let partsIds = params.works[i].partsIds.split(',');
								this.addCustompartslog({
									partId: partsIds[partsIds.length - 1],
									other: params.works[i].other,
									planId: res.data.planId || '',
									fromLocation: 'pageModules/barrierSearch/barrierPage'
								});
							}
						}

						setTimeout(() => {
							// 如果是维保员并且是任务指派的话跳转到维保详情
							if (
								this.userinfo.role_name == 'maintenance' &&
                this.activeIndex == 0
							) {
								console.log(res.data.planId, this.objData.elevatorId);
								uni.redirectTo({
									url:
                    '/subpages/repair/repariDetail?planId=' +
                    res.data.planId +
                    '&elevatorId=' +
                    this.objData.elevatorId,
									fail: (err) => {
										console.log(err);
									},
								});
							} else {
								// 跳转详情页(组长,转审批title值改变)
								let title =
                  this.userinfo.role_name == 'maintenance' ? '报障申请详情' : '报障审批详情';
								uni.redirectTo({
									url:
                    '/subpages/approve/repairDetail?planId=' +
                    res.data.planId +
                    '&elevatorId=' +
                    this.objData.elevatorId +
                    '&title=' +
                    title +
                    '&businessApproveId=' +
                    res.data.businessApproveId +
                    '&myApply=' +
                    (this.userinfo.role_name == 'maintenance' ? 1 : 2),
								});
							}
						}, 600);
					} else {
						uni.showToast({
							title: res.msg,
							icon: 'none',
						});
					}
				})
				.finally(() => {
					this.btnStatus = true;
				});
		}, 600),
		// 获取指定人列表
		handgetAssignMember() {
			// getAssignMemberList().then(res=>{ })
		},
		// 选择指派人
		radioClick() {
			// console.log("选择",e)
		},
		// 选项切换事件
		onChange(data, keyName) {
			let reData = data || {};
			switch (keyName) {
			case 'security':
				this.securityArr = reData;
				break;
			case 'faultArr':
				this.faultArr = reData;
				break;
			default:
				break;
			}
		},
		// 文本输入框
		bindTextAreaBlur(item, e) {
			if (e.detail.value) {
				item.mfDesc = e.detail.value;
			}
			item.tipsState = false;
			item.NumStr = this.bindTexStr(e.detail.value, 250);
		},
		bindTexStr(str, maxlength) {
			var result = '';
			if (str && str.length > maxlength) {
				result = maxlength;
			} else {
				result = str.length;
			}
			return result;
		},
		// 图片上传
		changeImg(item, imgArr = []) {
			item.mfImgUrl = imgArr;
			item.tipsState = false;
		},
		// 指派人点击
		personClick() {
			if (this.userinfo.role_name == 'maintenance') {
				return;
			}
			uni.navigateTo({
				url: '/pageModules/myApplication/assignTasks',
			});
			// this.show = !this.show
		},
		// 指派人 取消
		cancelClick() {
			this.show = false;
		},
		// 指派人 确定
		confirmClick() {
			this.show = false;
		},
		// 关闭modal
		closeModal() {
			this.show = false;
		},
		// 点击现象选择
		clickFaultItem(item, it) {
			if (!item.problemItem.includes(it.dictKey)) {
				item.problemItem.push(it.dictKey);
			} else {
				let faultIndex = item.problemItem.findIndex((e) => e == it.dictKey);
				item.problemItem.splice(faultIndex, 1);
			}
		},
		// 获取现象集合
		getProblemItem() {
			problemItem({}).then((res) => {
				if (res) {
					console.log(res, '集合');
					this.falutList = res.data;
					this.otherId = this.falutList.find(
						(item) => item.dictValue === '其他'
					).dictKey;
				}
			});
		},
	},
};
</script>

<style lang="scss" scoped>
page {
  background: #f3f6f8;
}

%widthMargin {
  width: 720rpx;
  margin: 0 auto;
}

.timeSe {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  padding: 0 10px;
  border-radius: 4px;
  background-color: #fff;
  color: #666;
  font-size: 14px;
  border: 2rpx solid #e9e9e9;

  .time_input {
    width: auto;
    height: 35px;
    padding-left: 5px;
    position: relative;
    flex: 1;
    line-height: 35px;
    font-size: 14px;
    overflow: hidden;
  }
}

.wrapperBA {
  height: calc(100vh - 100rpx);
  overflow-y: auto;
  overflow-x: hidden;

  .BA_item_top {
    // height: 166rpx;
    padding: 40rpx 20rpx 36rpx 20rpx;
    background: #2c2c2c;
    display: flex;
    flex-direction: column;
    justify-content: center;

    text:nth-child(1) {
      font-size: 36rpx;
      font-weight: 600;
      color: #ffffff;
      display: block;
    }

    text:nth-child(2) {
      display: block;
      font-size: 26rpx;
      font-weight: 400;
      color: #ffffff;
    }
  }

  .main {
    background: #f3f6f8;
    padding: 16rpx 20rpx;

    .mainBox {
      background-color: #fff;
      border-radius: 8rpx;
      margin-bottom: 16rpx;
    }
  }

  .serial-num {
    width: 40rpx;
    line-height: 40rpx;
    height: 40rpx;
    text-align: center;
    background: #dcf0ff;
    border-radius: 0px 0px 4rpx 4rpx;
    font-size: 24rpx;
    color: #0091FF;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .btnBox {
    display: flex;
    flex-wrap: wrap;

    .btn {
      width: 0;
      flex: 0 0 152rpx;
      border-radius: 4px;
      height: 48rpx;
      line-height: 48rpx;
      margin-bottom: 20rpx;
      display: flex;
      justify-content: center;
      align-items: center;
      margin-right: 20rpx;
    }

    .btn:nth-last-child(1) {
      margin-right: 0;
    }

    // .btn:nth-child(3n-1) {
    //   justify-content: center;
    // }

    // .btn:nth-child(3n + 3) {
    //   justify-content: flex-end;
    // }

    .btnItem {
      // border: 2rpx solid #cccccc;
      background-color: #dcf0ff;
      border-radius: 8rpx;
      color: #0091FF;
      font-size: 26rpx;
      width: 100%;
      line-height: 48rpx;
      height: 48rpx;
      display: flex;
      justify-content: center;
      align-items: center;
    }

    .btnSel {
      background-color: #0091ff;
      // border: 2rpx solid #0091ff;
      color: #ffffff;
    }
  }

  .repeatBox {
    .repeatBox_item {
      display: flex;
      align-items:
        center;
      justify-content:
        space-between;
      margin-bottom: 16rpx;
      margin-top: 20rpx;

      .handleBtn {
        display: flex;
        align-items: center;
      }

      image {
        width: 32rpx;
        height: 32rpx;
        cursor: pointer;
        margin-left: 20rpx;
      }

      .delBtn {
        color: #E02020;
        font-size: 24rpx;
        margin-left: 8rpx;
      }
    }
  }

  .BA_item_type {
    background-color: #ffffff;
    padding: 20rpx 20rpx 0rpx 20rpx;
    margin-bottom: 16rpx;
    border-radius: 8rpx;

    .title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;

      text {
        color: red;
      }

      &::before {
        content: '';
        display: inline-block;
        width: 4rpx;
        height: 32rpx;
        background-color: #0091ff;
        margin-right: 10rpx;
      }

      text {
        color: red;
      }
    }
  }

  .addMessage {
    width: 320rpx;
    margin: auto;
    margin-top: 20rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    image {
      width: 24rpx;
      height: 24rpx;
      margin-right: 10rpx;
    }

    .label {
      font-size: 28rpx;
      color: #0091ff;
    }
  }

  .BA_item_info {
    margin-top: 20rpx;
    padding: 24rpx 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 8rpx;

    .title {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
    }

    .selected {
      border-color: #0091ff !important;
      color: #0091ff !important;
    }

    .radio {
      display: flex;
      align-items: center;
      border: 2rpx solid #cccccc;
      border-radius: 8rpx;
      padding: 4rpx 10rpx;
      color: #666;

      .right-check {
        width: 30rpx;
        height: 30rpx;
        border-radius: 50%;
        border: 2rpx #cccccc solid;
        margin-right: 10rpx;
      }

      .right-bg {
        border: none;
        // background-color: #0091FF;
        background: url("");
        background-size: 32rpx 32rpx;
        background-repeat: no-repeat;
      }
    }

    .item_partsModel {
      margin-top: 20rpx;
      margin-bottom: 12rpx;

      .title {
        font-size: 28rpx;
        color: #666666;
        margin: 16rpx 0;

        text {
          color: red;
        }
      }

      .partsNumber_select {
        display: flex;
        flex-direction: row;
        margin-bottom: 32rpx;
        padding: 10rpx 20rpx;
        border: 2rpx solid #e9e9e9;
        border-radius: 8rpx;

        .innerText {
          font-size: 28rpx;
          font-family: PingFangSC, PingFangSC-Regular;
          font-weight: 400;
          text-align: left;
          align-items: center;
          color: #cccccc;
          line-height: 40rpx;
          width: 80%;
        }

        .downs {
          width: 40rpx;
          margin-left: auto;
          // padding-top: 28rpx;

          text {
            display: inline-block;
            width: 16rpx;
            height: 16rpx;
            border-bottom: 2rpx #ccc solid;
            border-left: 2rpx #ccc solid;
            transform: rotate(-45deg);
          }
        }
      }

      .partsNumber_input {
        width: 630rpx;
        border: 2rpx solid #e9e9e9;
        border-radius: 8rpx;
        padding: 10rpx 20rpx;
        border-right: 0px;
        border-radius: 8rpx 0rpx 8rpx 8rpx
      }

      .falutContent {
        display: flex;
        flex-wrap: wrap;
      }

      .falutItemBox {
        display: flex;
        width: 33.3%;
        margin-bottom: 20rpx;
      }

      .falutItemBox:nth-child(3n-1) {
        justify-content: center;
      }

      .falutItemBox:nth-child(3n + 3) {
        justify-content: flex-end;
      }

      .falutItem {
        border: 2rpx solid #cccccc;
        border-radius: 8rpx;
        color: #666;
        font-size: 26rpx;
        width: 216rpx;
        height: 48rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .active {
        color: #0091ff;
        border-color: #0091ff;
      }

      .other {
        width: 670rpx;
        height: 72rpx;
        border: 2rpx solid #e9e9e9;
        border-radius: 4rpx;
        padding-left: 28rpx;
        box-sizing: border-box;
      }
    }

    .item_desc {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        font-size: 28rpx;
        color: #666;
        margin-bottom: 0;

        text {
          color: red;
        }
      }

      view:nth-child(2) {
        font-size: 24rpx;
        color: #999999;

      }
    }

    .info_head {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
      display: flex;
      align-items: center;

      // margin-bottom: 20rpx;
      &::before {
        content: '';
        display: inline-block;
        width: 4rpx;
        height: 32rpx;
        background-color: #0091ff;
        margin-right: 10rpx;
      }

      text {
        color: red;
      }
    }

    .areaBox {
      padding: 20rpx 24rpx;
      border: 2rpx solid #e9e9e9;
      border-radius: 8rpx;
      margin-top: 20rpx;
      margin-bottom: 32rpx;
    }

    .info_num {
      text-align: right;
      font-size: 24rpx;
      font-weight: 400;
      color: #666666;
    }

    .info_img {
      margin-top: 20rpx;
      margin-bottom: 28rpx;

      view:nth-child(1) {
        color: #666;
        font-size: 28rpx;
        margin-bottom: 20rpx
      }

      // display: flex;
      text {
        display: block;
        margin: 10rpx 0;
        font-size: 24rpx;
        font-weight: 400;
        color: #e02020;
      }
    }

    textarea {
      width: 100%;
    }
  }

  .BA_item_person {
    margin-top: 20rpx;
    padding: 24rpx 20rpx 20rpx 20rpx;
    background-color: #ffffff;
    border-radius: 8rpx;

    .title {
      margin-bottom: 34rpx;
      display: flex;
      align-items: center;

      // margin-bottom: 20rpx;
      &::before {
        content: '';
        display: inline-block;
        width: 4rpx;
        height: 32rpx;
        background-color: #0091ff;
        margin-right: 10rpx;
      }
    }

    .sign {
      color: #e02020;
    }

    .title {
      font-size: 32rpx;
      font-weight: 600;
      color: #333333;
    }

    .person {
      margin-bottom: 30rpx;
      display: flex;
      flex-direction: row;

      .personL {
        display: flex;
        align-items: center;
        flex: 1;
        font-size: 28rpx;
        font-weight: 400;
        color: #666666;
      }

      .personR {
        flex: 0 0 500rpx;
        font-size: 28rpx;
        font-weight: 400;
        color: #666;
        align-items: center;
        display: flex;
        justify-content: flex-end;

        view {
          width: 500rpx;
        }

        // text:nth-child(1){
        //  font-size: 28rpx;
        //  font-weight: 400;
        //  color: #999999;
        //  display: inline-block;
        //  margin: 0 10rpx;
        // }
        .rightTo {
          display: inline-block;
          width: 16rpx;
          height: 16rpx;
          border-bottom: 1rpx #999999 solid;
          border-right: 1rpx #999999 solid;
          transform: rotate(-45deg);
          margin-left: 10rpx;
        }
      }
    }
  }

  .BA_item_tips {
    margin: 20rpx 0 40rpx 0;
    padding: 20rpx;
    font-size: 24rpx;
    font-weight: 400;
    color: #999999;
  }

  .BA_item_botm {
    position: fixed;
    bottom: 0;
    left: 0;
    z-index: 99;
    height: 98rpx;
    display: flex;
    align-items: center;
    width: 100%;
    background: #fff;

    .botm {
      @extend %widthMargin;
      height: 70rpx;
      background: #0091ff;
      border-radius: 8rpx;
      line-height: 70rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 500;
      color: #ffffff;
    }

    .botms {
      @extend %widthMargin;
      height: 70rpx;
      background: #efefef;
      border-radius: 8rpx;
      line-height: 70rpx;
      text-align: center;
      font-size: 28rpx;
      font-weight: 500;
      color: #cccccc;
    }
  }

  .radioLR {
    display: flex;
    flex-direction: row;
    // height: 103rpx;
    // line-height: 103rpx;

    .radio_R {
      flex: 1;
      display: flex;
      flex-direction: row;
      border-bottom: 2rpx #eeeeee solid;

      view:nth-child(1) {
        flex: 1;
      }

      // view:nth-child(2){
      //   flex:  0 0 80rpx;
      // }
    }
  }

  .radioLR:last-child {
    .radio_R:last-child {
      border-bottom: none;
    }
  }
}

/deep/.helange-btns {
  .container {
    .views {
      width: 0;
      flex: 0 0 152rpx;
      margin-right: 20rpx !important;

      .item {
        border: none;
        background-color: #dcf0ff;
        border-radius: 8rpx;
        color: #0091FF;
        font-size: 26rpx;
        width: 100% !important;
        line-height: 48rpx;
        height: 48rpx;
        display: flex;
        justify-content: center;
        align-items: center;
      }

      .active {
        border: none;
        background-color: #0091ff;
        color: #ffffff;
      }
    }
  }
}

.comfirBox {
  text-align: center;
  color: #333;
  font-size: 24rpx;

  .tips {
    color: #e02020;
    padding: 10rpx 0;
    font-size: 24rpx;
  }

  ;
}
</style>
